package top.chenfu.security.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.chenfu.security.dao.UserDao;
import top.chenfu.security.entity.Role;
import top.chenfu.security.entity.User;
import top.chenfu.security.service.UserService;

import java.util.List;
import java.util.Objects;

/**
 * @Auther chenfu
 * @2019/10/29 13:06
 * @Desc
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查出用户的角色信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @Cacheable(value = "hashCache", key = "'redis_user_'+#username")
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        此种方式会出现问题，问题出在数据库查的数据，enabled字段的set方法失效
//        Example example = new Example(User.class);
//        example.and().andEqualTo("username", username);
//        User user = userDao.selectOneByExample(example);
        User user = userDao.selectOneByUsername(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("没有该用户");
        }
        List<Role> roles = userDao.selectRolesByUserId(user.getId());
        user.setRoles(roles);
        return user;
    }

}
